import gradio as gr
from PIL import Image, ImageOps, ImageChops
from utils import generate_random_dir, generate_random_file
from utils.ps_canvas import PSTools
from face68 import Face68
import os
from demo_models import face68_model


def main(origin_image: Image) -> Image:
    # 设置数据缓存目录
    _save_dir = generate_random_dir()
    # 数据先保存
    origin_filename = generate_random_file(dir_=_save_dir)
    origin_image.save(origin_filename)
    # 调模型
    try:
        model = face68_model
        result = model.get_keypoints_info(
            image_path=origin_filename,
            save_dir=_save_dir)
        image = Image.open(result.image_path)
        json_ = {
            "图片width": result.image_wdith,
            "图片height": result.image_height,
            "人脸width": result.face_width,
            "人脸height": result.face_height,
            "人脸中心坐标": result.center,
            "人脸下颚坐标(第8个点)": result.point_8,
        }
    except Exception as e:
        logger.exception(str(e))
        image = None
        json_ = {}
    os.system(f"rm -rf {_save_dir}")
    return image, json_


def demo():
    with gr.Row():
        origin_image = gr.Image(type="pil", label="原始图像")
        out_json = gr.JSON(label="68点关键信息")
        out_image = gr.Image(type="pil")
    gr.Button("运行").click(main, inputs=[
        origin_image], outputs=[out_image, out_json])
